package com.lv.suyiyong.hfrbusines.fragment

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.SizeUtils
import com.google.android.material.imageview.ShapeableImageView
import com.google.gson.reflect.TypeToken
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseFragment
import com.lv.common.bean.CustomMessageBean
import com.lv.common.bean.CustomMessageChatBean
import com.lv.common.imp.OnPositionTListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.LogUtil
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration

import com.lv.service.adapter.HomeTabAdapter
import com.lv.service.bean.CommonSelectedBean
import com.lv.service.bean.CommonTab
import com.lv.service.event.HomeTabChangeEvent
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.utils.YgxAroutPageKt
import com.lv.service.weidget.picker.ListSingleTextPopupView
import com.lv.suyiyong.hfrbusines.R
import com.lv.suyiyong.hfrbusines.databinding.FragmentHomeBinding
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMConversation
import com.tencent.imsdk.v2.V2TIMConversationListener
import com.tencent.imsdk.v2.V2TIMConversationResult
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMMessage
import com.tencent.imsdk.v2.V2TIMValueCallback
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback


/**
 * 作者： ygx
 * 创建日期：2023/2/10 11:24 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：应用商城需要的权限：ABCDEFGHIJKLMNO
 */
class HomeFragment : BaseFragment() {
    private val mBeans = mutableListOf<CommonTab>()
    private val mOnLineBeans = mutableListOf<CommonSelectedBean>()
    private var mAdapter: HomeTabAdapter? = null
    private var mUserInfo: UserInfo? = null
    private var mOnLine = "0"
    private var mIvLogo: ShapeableImageView? = null
    private var mIvMore: ImageView? = null
    private var mTvMessageText: TextView? = null
    private var mTvMsgTotalUnread: TextView? = null
    private var mViewChatBg: View? = null
    private var mBinding: FragmentHomeBinding? = null

    override fun getLayoutRes() = R.layout.fragment_home
    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentHomeBinding.bind(view).apply {
            mTvMessageText = tvMessageText
            mTvMsgTotalUnread = msgTotalUnread
            mViewChatBg = viewChatBg
            mIvMore = ivMore
            userInfo = mUserInfo
            StatusBarUtil.setHeightAndPadding(requireContext(), tvTitle)

            val gridLayoutManager = GridLayoutManager(requireContext(), 3)
            mAdapter = HomeTabAdapter(mBeans)
            adapter = mAdapter
            rvContent.layoutManager = gridLayoutManager
            rvContent.addItemDecoration(
                SpacesItemDecoration(
                    SizeUtils.dp2px(19.0f),
                    SizeUtils.dp2px(0f),
                    false
                )
            )
//            ivLogo.setOnClickListener {
//                val json = GsonUtils.toJson(mImageBeans)
//                ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
//                    .withInt("position", 0)
//                    .withString("data", json)
//                    .navigation()
//            }
        }

        return mBinding!!
    }

    override fun initConfig() {
        super.initConfig()
        mBinding?.rvContent?.visibility = View.GONE
        mOnLineBeans.clear()
        mOnLineBeans.add(CommonSelectedBean("书刊推广数据", selected = true))
        mOnLineBeans.add(CommonSelectedBean("APP推广数据", selected = false))
        /*// 获取定位信息后的回调，
        locationUtil.locationCallBack = {
            val address = locationUtil.getAddress(requireContext(), it)
            try {
                val city = "${address?.locality}"
//                val town = address?.getAddressLine(0)
                var featureName = address?.featureName
                if (featureName.isNullOrEmpty()) {
                    featureName = address?.thoroughfare + address?.subThoroughfare
                }
                SPStaticUtils.put(Constants.ADDRESS_CITY_RECEIPT_KEY, city)
                SPStaticUtils.put(Constants.ADDRESS_TOWN_RECEIPT_KEY, featureName)
            } catch (e: Exception) {
            }
        }*/
        UserDbHelper.getLiveUserInfo(requireContext()).observeKt { userInfo ->
            if (userInfo != null && userInfo.id.isNotEmpty()) {
                mUserInfo = userInfo
                mIvLogo?.LoadSrc(userInfo.logo)
                val role = userInfo.role ?: ""
                mBeans.clear()
                mBeans.add(CommonTab("", "", "工作台", 0, true))
                mBeans.add(
                    CommonTab(
                        "0", "j", "亨富然", com.lv.common.R.drawable.bg_color_theme_buttom_5, false
                    )
                )
//                if (role.contains("A")) {
//                    mBeans.add(
//                        CommonTab(
//                            "", "A", "开户", R.drawable.icon_open_company_manager, false
//                        )
//                    )
//                }
//                if (role.contains("B")) {
//                    mBeans.add(CommonTab("", "B", "回执", R.drawable.icon_receipt_manager, false))
//                }
//                if (role.contains("C")) {
//                    mBeans.add(
//                        CommonTab(
//                            "", "C", "回执拍照", R.drawable.icon_home_receipt_camare, false
//                        )
//                    )
//                }
//                if (role.contains("D")) {
//                    mBeans.add(CommonTab("", "D", "附近商铺绑卡", R.drawable.icon_join_syy, false))
//                }
//                if (role.contains("E")) {
//                    mBeans.add(CommonTab("", "E", "附近商铺", R.drawable.icon_zhdq_manager, false))
//                }
//                if (role.contains("F")) {
//                    mBeans.add(CommonTab("", "F", "卡包", R.drawable.icon_card_page_manager, false))
//                }
//                if (role.contains("G") || role.contains("D") || role.contains("E") || role.contains(
//                        "F"
//                    )
//                ) {
//                    mBeans.add(
//                        CommonTab(
//                            "", "G", "附近商铺统计", R.drawable.icon_zhdqtongji_manager, false
//                        )
//                    )
//                }
//                if (role.contains("H") || role.contains("B") || role.contains("C")) {
//                    mBeans.add(
//                        CommonTab(
//                            "", "H", "回执统计", R.drawable.icon_receipt_tongji_manager, false
//                        )
//                    )
//                }
//                if (role.contains("I")) {
//                    mBeans.add(CommonTab("0", "I", "电子书刊", R.drawable.icon_book_manager, false))
//                }
//                if (role.contains("J")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "J", "电子回执", R.drawable.icon_home_book_tag, false
//                        )
//                    )
//                }
//
//                if (role.contains("X")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "L", "开通免费店铺", R.drawable.icon_xjqtji, false
//                        )
//                    )
//                }
//                if (role.contains("b")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "b", "返现统计", R.drawable.icon_fxtji, false
//                        )
//                    )
//                }
//                if (role.contains("c")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "c", "广告统计", R.drawable.icon_ggwtj, false
//                        )
//                    )
//                }
//                if (role.contains("e")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "e", "金牌切换统计", R.drawable.icon_jpqiehuan, false
//                        )
//                    )
//                }
//                if (role.contains("f")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "f", "店铺充值统计", R.drawable.icon_czhitjji, false
//                        )
//                    )
//                }
//                if (role.contains("h")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "h", "推广统计", R.drawable.icon_push_statistic, false
//                        )
//                    )
//                }
//                if (role.contains("i")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "i", "拜访记录统计", R.drawable.icon_bfjl, false
//                        )
//                    )
//                }
                mAdapter?.notifyDataSetChanged()
                mBinding?.rvContent?.visibility = View.VISIBLE
            } else {
                mUserInfo = null
                mBinding?.rvContent?.visibility = View.GONE
                mIvLogo?.LoadSrc(0)
            }
        }


    }

    override fun initData() {
        super.initData()

        // 1. 设置会话监听
        V2TIMManager.getConversationManager().addConversationListener(v2TIMConversationListener)
        // 2. 先拉取50个本地会话做 UI 展示，nextSeq 第一次拉取传0
        V2TIMManager.getConversationManager().getConversationList(
            0, 50,
            object : V2TIMValueCallback<V2TIMConversationResult?> {
                override fun onSuccess(v2TIMConversationResult: V2TIMConversationResult?) {
                    val nextSeq = v2TIMConversationResult?.nextSeq
                    LogUtils.e(
                        "imsdk",
                        "success nextSeq:" + nextSeq + ", isFinish:" + v2TIMConversationResult?.isFinished
                    )
                    val v2TIMConversationList = v2TIMConversationResult?.conversationList
                    v2TIMConversationList?.let {
                        refreshHomeRing(v2TIMConversationList)
                    }

                }

                override fun onError(code: Int, desc: String) {
                    LogUtils.e("imsdk", "failure, code:$code, desc:$desc")
                }


            })

    }

    private val v2TIMConversationListener: V2TIMConversationListener =
        object : V2TIMConversationListener() {
            // 3.1 收话新增的回调
            @RequiresApi(api = Build.VERSION_CODES.N)
            override fun onNewConversation(conversationList: List<V2TIMConversation>) {
                super.onNewConversation(conversationList)
                LogUtil.e("onNewConversation", "onNewConversation")
            }

            // 3.2 收到会话更新的回调
            @RequiresApi(api = Build.VERSION_CODES.N)
            override fun onConversationChanged(conversationList: List<V2TIMConversation>) {
                if (conversationList.isEmpty()) {
                    return
                }
                val v2TIMConversation = conversationList[0]
                checkLoginOtherDevice(v2TIMConversation)
                refreshHomeRing(conversationList)

            }
        }
    private val mMessages = mutableListOf<V2TIMConversation>()

    private fun refreshHomeRing(conversationList: List<V2TIMConversation>) {
        for (i in conversationList.indices) {
            val conv = conversationList[i]
            var isExit = false
            for (j in mMessages.indices) {
                val uiConv = mMessages[j]
                // UI 会话列表存在该会话，则替换
                if (uiConv.conversationID == conv.conversationID) {
                    mMessages[j] = conv
                    isExit = true
                    break
                }
            }
            // UI 会话列表没有该会话，则新增
            if (!isExit) {
                mMessages.add(conv)
            }
        }
        val messages = mutableListOf<V2TIMConversation>()
        mMessages.let {
            it.forEach { item ->
                val unreadCount = item.unreadCount
                if (unreadCount > 0) {
                    messages.add(item)
                }
            }
        }

        if (messages.isNotEmpty()) {
            messages.sortByDescending { item -> item.lastMessage.timestamp }
            val v2TIMConversation = messages[0]
            var conversationID = v2TIMConversation.conversationID
            val unreadCount = v2TIMConversation.unreadCount
            mTvMsgTotalUnread?.text = "$unreadCount"
            mIvMore?.visibility = if (unreadCount > 0) View.VISIBLE else View.GONE
            mTvMsgTotalUnread?.visibility = if (unreadCount > 0) View.VISIBLE else View.GONE
            if (conversationID.startsWith("c2c_")) {
                conversationID = conversationID.drop(4)
            }
            if (conversationID.contains("syy0000")) {
                val customText = v2TIMConversation.lastMessage.customElem
//                var dataCustom = customText ?: return
                if (customText == null) {
                    initChatMessage()
                    return
                }
                val customJson = customText.data.toString(Charsets.UTF_8)
                val jsonType = object : TypeToken<CustomMessageChatBean?>() {}.type
                val jt: CustomMessageChatBean = GsonUtils.fromJson(customJson, jsonType)
//                val t = jt.t
//                val ti = jt.ti
//                val tt = jt.tt
//                val sender = jt.sender
                if (activity != null) {
                    YgxAroutPageKt.aroutPager(requireContext(), jt, mViewChatBg)
                }

                when (conversationID) {

                    Constants.SYY_YWY_FXXX -> {//风险下线
                        mTvMessageText?.text = "您有新的风险下线消息"
                    }

                    Constants.SYY_YWY_SHTZ -> {//审核通知
                        mTvMessageText?.text = "您有新的审核通知"

                    }

                    Constants.SYY_YWY_GQTZ -> {//过期通知
                        mTvMessageText?.text = "您有新的过期通知"

                    }

                    Constants.SYY_YWY_KHSQ -> {//开户申请
                        mTvMessageText?.text = "您有新的开户申请"

                    }

                    Constants.SYY_YWY_ZHDQ -> {//找货大全
                        mTvMessageText?.text = "您有新的附近商铺消息"

                    }

                    Constants.SYY_YWY_SJXX -> {//商机消息
                        mTvMessageText?.text = "您有新的商机消息"

                    }

                    Constants.SYY_YWY_SP -> {//审批
                        mTvMessageText?.text = "您有新的审批通知"

                    }

                    Constants.SYY_YWY_RYBD -> {//人员变动
                        mTvMessageText?.text = "您有新的人员变动消息"

                    }

                    Constants.SYY_YWY_BWLCS -> {//财务抄送
                        mTvMessageText?.text = "您有新的抄送消息"
                    }

                    Constants.SYY_YWY_BIRTHDAY -> {//生日提醒
                        mTvMessageText?.text = "您有生日提醒消息"
                    }

                    Constants.SYY_YWY_FIND_GOODS -> {//我要找货
                        mTvMessageText?.text = "您有新的我要找货消息"
                    }

                    Constants.SYY_YWY_ZDSJ -> {//我要找货
                        mTvMessageText?.text = "您有新的指定商家接单消息"
                    }

                    Constants.SYY_YWY_ZRSP -> {//转入审批
                        mTvMessageText?.text = "您有新的转入审批消息"
                    }

                    Constants.SYY_YWY_REFUND -> {//退款审批
                        mTvMessageText?.text = "您有新的退款审批消息"
                    }

                    Constants.SYY_YWY_CZFX -> {//充值返现
                        mTvMessageText?.text = "您有新的充值返现消息"
                    }

                    else -> {
                        mTvMessageText?.text = "未知消息"

                    }

                }

            } else {
//                val userID = v2TIMConversation.userID
//                val showName = v2TIMConversation.showName
//                TUIUtils.startChat(userID, showName, V2TIMConversation.V2TIM_C2C)
            }
        } else {
            initChatMessage()
        }
    }

    private fun initChatMessage() {
        mTvMsgTotalUnread?.visibility = View.GONE
        mIvMore?.visibility = View.GONE
        mTvMessageText?.text = "消息通知"
        mViewChatBg?.setOnClickListener {
            //跳转到消息Tab
            LiveEventBus
                .get(HomeTabChangeEvent::class.java)
                .post(HomeTabChangeEvent("", 2))
        }
    }

    private fun checkLoginOtherDevice(v2TIMConversation: V2TIMConversation) {
        val chatTag = SPStaticUtils.getString(Constants.KEY_CHAT_TOKEN, "aaa")
        val userID = v2TIMConversation.userID
        if (mUserInfo?.txaccid == userID) {
            val customText = v2TIMConversation.lastMessage.customElem
            val customJson = customText.data.toString(Charsets.UTF_8)
            val jsonType = object : TypeToken<CustomMessageBean?>() {}.type
            val jt: CustomMessageBean = GsonUtils.fromJson(customJson, jsonType)
            val idSyyAccid = jt.id_syy_accid
            if (idSyyAccid.isEmpty() || !idSyyAccid.contains("速易甬")) {
                return
            }
            val split = idSyyAccid.split("速易甬".toRegex()).toTypedArray()
            if (split.size < 3) {
                return
            }
            if (mUserInfo?.txaccid != split[1]) {
                return
            }
            if (mUserInfo?.phone != split[2]) {
                return
            }
//            V2TIMManager.getConversationManager().cleanConversationUnreadMessageCount(
//                String.format("c2c_%s", mUserInfo?.txaccid), 0, 0, object : V2TIMCallback {
//                    override fun onSuccess() {
//                        LogUtils.e("onSuccess:cleanConversationUnreadMessageCount===${mUserInfo?.txaccid}")
//                    }
//
//                    override fun onError(i: Int, s: String) {
//                        LogUtils.e("onError:cleanConversationUnreadMessageCount===${mUserInfo?.txaccid}")
//
//                    }
//                })
            if (!TextUtils.isEmpty(chatTag) && chatTag != "aaa" && split[0] != chatTag) {
                TUILogin.logout(object : TUICallback() {
                    override fun onSuccess() {
                        YgxUtilsKt.setAppToken("", "", "")
                        V2TIMManager.getConversationManager()
                            .removeConversationListener(null)
                        ARouter.getInstance().build(ARoutUtils.LoginOutActivity).navigation()

//                        showLoginOutDialog()
                    }

                    override fun onError(errorCode: Int, errorMessage: String?) {
                    }
                })

            }
        } else {
        }
    }


    override fun initEvents() {
        super.initEvents()
        mAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
            if (!data.isNullOrEmpty()) {
                when (data) {
                    "j" -> {//亨富然
                        ARouter.getInstance()
                            .build(ARoutUtils.ClientsHFRActivity).navigation()
                    }
//                    "A" -> {//开户
//                        ARouter.getInstance().build(ARoutUtils.OpenCompanyActivity)
//                            .navigation()
//
//                    }
//
//                    "B" -> {//回执列表
//                        ARouter.getInstance().build(ARoutUtils.ReceiptActivity)
//                            .withString("name", mUserInfo?.name)
//                            .navigation()
//                    }
//
//                    "C" -> {//回执拍照
//                        checkPermissionLoction()
//                    }
//
//                    "D" -> {//入驻速易甬
//                        ARouter.getInstance().build(ARoutUtils.CardBindActivity)
//                            .navigation()
//                    }
//
//                    "E" -> {//附近商铺
//                        ARouter.getInstance().build(ARoutUtils.CompanyClientActivity)
//                            .navigation()
//                    }
//
//                    "F" -> {//卡包
//                        ARouter.getInstance().build(ARoutUtils.CardPackageActivity)
//                            .navigation()
//                    }
//
//                    "G" -> {//附近商铺统计
//                        val role = mUserInfo?.role ?: ""
//                        if (role.contains("G")) {
//                            ARouter.getInstance().build(ARoutUtils.ContractsActivity)
//                                .withInt("type", 1)
//                                .navigation()
//                        } else {
//                            ARouter.getInstance().build(ARoutUtils.ContractsStatisticActivity)
//                                .withString("phone", mUserInfo?.id).navigation()
//                        }
//                    }
//
//                    "H" -> {//回执统计
//                        val role = mUserInfo?.role ?: ""
//                        if (role.contains("H")) {
//                            ARouter.getInstance().build(ARoutUtils.ContractsActivity)
//                                .withInt("type", 2)
//                                .navigation()
//                        } else {
//                            ARouter.getInstance().build(ARoutUtils.ReceiptStatisticActivity)
//                                .withString("phone", mUserInfo?.id).navigation()
//                        }
//                    }
//
//                    "I" -> {//电子书刊
//                        ARouter.getInstance().build(ARoutUtils.BookActivity)
//                            .navigation()
//                    }
//
//                    "J" -> {//电子回执
//                        ARouter.getInstance().build(ARoutUtils.BookHZActivity)
//                            .navigation()
//
//                    }
//
//                    "K" -> {//现金券统计
//                        ARouter.getInstance().build(ARoutUtils.QuanTabActivity)
//                            .navigation()
//
//                    }
//
//                    "L" -> {//开通免费店铺
//                        ARouter.getInstance().build(ARoutUtils.FreeCompanyListActivity)
//                            .navigation()
//
//                    }
//
//                    "b" -> {//返现统计-地区选择
////                        val boss = mUserInfo?.isBoss() ?: false
////                        val bpro = mUserInfo?.bpro
////                        val split = bpro?.split("_")
////                        if (!boss && split?.size == 1) {
////                            ARouter.getInstance().build(ARoutUtils.CouponStatisticsActivity)
////                                .withString("province", split[0])
////                                .navigation()
////                        } else {
////                        }
//                        ARouter.getInstance().build(ARoutUtils.AddressSelectedActivity)
//                            .navigation()
//
//                    }
//
//                    "c" -> {//广告统计-地区选择
////                        val boss = mUserInfo?.isBoss() ?: false
////                        val bpro = mUserInfo?.bpro
////                        val split = bpro?.split("_")
////                        if (!boss && split?.size == 1) {
////                            ARouter.getInstance().build(ARoutUtils.ADStatisticsActivity)
////                                .withString("province", split[0])
////                                .navigation()
////                        } else {
////                        }
//                        ARouter.getInstance().build(ARoutUtils.AddressSelectedActivity)
//                            .withInt("type", 1)
//                            .navigation()
//
//                    }
//
//                    "e" -> {//金牌切换统计
//                        ARouter.getInstance().build(ARoutUtils.GoldClientStatisticsTabActivity)
//                            .withParcelable("userInfo", mUserInfo)
//                            .navigation()
//
//                    }
//
//                    "f" -> {
//                        ARouter.getInstance().build(ARoutUtils.CompanyRechargeStatisticsActivity)
//                            .withParcelable("userInfo", mUserInfo)
//                            .navigation()
//                    }
//
//                    "h" -> {//推广统计
//                        ARouter.getInstance().build(ARoutUtils.PushStatisticsActivity)
////                            .withParcelable("userInfo", mUserInfo)
//                            .navigation()
//                    }
//
//                    "i" -> {
//                        ARouter.getInstance().build(ARoutUtils.AddressSelectedActivity)
//                            .withInt("type", 2)
//                            .navigation()
//                    }
//
////                    "I" -> {//进销存
////                        showToast(data)
////
////                    }
                }
            }

        }
        addToBlackList()
//        rigestEventBus()
    }

    private fun checkPermissionLoction() {
        val permissions = mutableListOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION,
        )
        // 用于在您浏览、搜索或参与特定活动时，向您展示当前城市服务信息，以提升体验。不申请该权限不影响APP的正常使用。是否同意去申请该权限？
        PermissionXUtils.checkPermissBefore(
            this,
            permissions,
            "上传回执需要授予位置权限，用于展示当前城市的服务信息，以提升体验。不申请该权限不影响APP的正常使用。",
            object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>,
                ) {
                    if (allGranted) {
                        showLineSelected()
//                        locationUtil.initLocationManager()
//                        LocationUtils.getInstance().getLocations(requireContext())

                    }
                }


            },
        )
    }

    private fun showLineSelected() {
        val popupView = ListSingleTextPopupView(
            requireContext(), mOnLineBeans
        ) { position, data ->
            when (position) {
                0, 1 -> {
//                    mOnLine = "$position"
//                    ARouter.getInstance().build(ARoutUtils.CameraCustomActivity)
//                        .withString("type", "0")
//                        .withString("online", mOnLine)
//                        .withString("name", mUserInfo?.name ?: "")
//                        .navigation()
//                    SPStaticUtils.put(Constants.KEY_POS_HZ_P_ONLINE, mOnLine)

                }
            }
        }
        XPopup.Builder(requireContext())
            .isViewMode(true)
            .popupPosition(PopupPosition.Bottom)
            .asCustom(popupView)
            .show()
    }

    private fun addToBlackList() {
        // 设置在线和离线都不接收消息
        val userList: MutableList<String> = ArrayList()
        userList.add(Constants.ID_FW_OLD)
        userList.add(Constants.ID_HD_OLD)
        userList.add(Constants.ID_TZ_OLD)

        V2TIMManager.getMessageManager().setC2CReceiveMessageOpt(
            userList,
            V2TIMMessage.V2TIM_NOT_RECEIVE_MESSAGE,
            object : V2TIMCallback {
                override fun onSuccess() {
                    LogUtils.e("imsdk", "success")
                }

                override fun onError(code: Int, desc: String) {
                    LogUtils.e("imsdk", "failure, code:$code, desc:$desc")
                }
            })

    }

//    private fun rigestEventBus() {
//        LiveEventBus.get(
//            HomeRefreshEvent::class.java,
//        ).observe(
//            this
//        ) { s ->
//            if (s != null) {
//                val message = s.message
//                val offlineMessageBean = s.offlineMessage
//                val pushMessage = s.pushMessage
//                if (message != null) {
//                    val conversationID = message.conversationID
//                    val unreadCount = message.unreadCount
//                    mTvMsgTotalUnread?.text = "$unreadCount"
//                    mTvMsgTotalUnread?.visibility = if (unreadCount > 0) View.VISIBLE else View.GONE
//                    if (conversationID.contains("syy0000")) {
//                        if (conversationID == Constants.ID_TZ) {
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        } else if (conversationID == Constants.ID_FW) {
//                            ARouter.getInstance().build(ARoutUtils.MessageVisitRecodeActivity)
//                                .navigation()
//                        } else if (conversationID == Constants.ID_HD) {
//                            ARouter.getInstance().build(ARoutUtils.MessageInteractionActivity)
//                                .navigation()
//                        }
//
//                    } else {
//                        mTvMessageText?.text = "新增聊天消息"
//                        mViewChatBg?.setOnClickListener {
//                            //点击后，页面切换到消息Tab
//                            val showName = message.showName
//                            TUIUtils.startChat(
//                                conversationID,
//                                showName,
//                                V2TIMConversation.V2TIM_C2C
//                            )
//                        }
//                    }
//                    mIvMore?.visibility = View.VISIBLE
//                }
//                if (offlineMessageBean != null) {
//                    if (offlineMessageBean.action == OfflineMessageBean.REDIRECT_ACTION_CHAT) {
//                        if (TextUtils.isEmpty(offlineMessageBean.sender)) {
//                            return@observe
//                        }
//                        TUIUtils.startChat(
//                            offlineMessageBean.sender,
//                            offlineMessageBean.nickname,
//                            offlineMessageBean.chatType
//                        )
//                    }
//                }
//                if (pushMessage != null) {
//                    when (pushMessage.t) {
//                        "100" -> {//完善信息
//                            mTvMessageText?.text = "重要通知"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "102" -> {//书刊上新
//                            mTvMessageText?.text = "书刊上新"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "103" -> {// 商品风险下架
//                            mTvMessageText?.text = "商品风险下架"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "104" -> {// 货圈风险下架
//                            mTvMessageText?.text = "货圈风险下架"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//
//                        }
//                        "105" -> {// 货圈审核通过
//                            mTvMessageText?.text = "审核通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "106" -> {// 106 货圈审核未通过
//                            mTvMessageText?.text = "审核未通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//
//                        "107" -> {// 商品上架通过
//                            mTvMessageText?.text = "审核通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "108" -> {// 商品上架拒绝
//                            mTvMessageText?.text = "审核未通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "110" -> {// 访问消息
//                            ARouter.getInstance().build(ARoutUtils.MessageVisitRecodeActivity)
//                                .navigation()
//                        }
//                        "111", "112", "113", "114" -> {// 111 点赞货圈 112 关注店铺 113  收藏商品 114  拨打电话
//                            ARouter.getInstance().build(ARoutUtils.MessageInteractionActivity)
//                                .navigation()
//                        }
//                        else -> {
//
//                        }
//                    }
//                }
//
//            }
//        }
//    }
//    override fun isHaveHeadMargin(): Boolean {
//        return false
//    }

    companion object {
        @JvmStatic
        fun newInstance() = HomeFragment()
    }

    override fun onResume() {
        super.onResume()
        LogUtils.e("onResume")
//        initStatusBar(requireActivity(), true, false)
    }

//    override fun onHiddenChanged(hidden: Boolean) {
//        super.onHiddenChanged(hidden)
//        LogUtils.e("onHiddenChanged==$hidden")
//        if (!hidden) {
//            initStatusBar(requireActivity(), true, false)
//        }
//    }


    override fun onDestroy() {
        super.onDestroy()
    }

//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if (data != null) {
//            //QQ回调
//            ShareUtils.get().onQqActivityResult(requestCode, resultCode, data)
//        }
//    }
}